package com.example.projects;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.OverlayItem;
import com.google.android.maps.Projection;

public class GoogleMaps extends GoogleMapsMenu {
private MapView map=null;
private MyLocationOverlay me=null;
private Context context = this;
private Projection projection;
private List<OverlayItem> items=new ArrayList<OverlayItem>();

private LocationDetails[] locations=null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.google_maps);
	   
		map=(MapView)findViewById(R.id.mapView);
	
		//map.getController().setZoom(17);
		map.setBuiltInZoomControls(true);
		    
		Drawable marker=getResources().getDrawable(R.drawable.mapmarker);
		    
		marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker.getIntrinsicHeight());
		
		String str = "";
		String namestr = "";
		String descriptionstr = "";
		String latitudestr = "";
		String longitudestr = "";
		String imagestr = "";
		String locstr = "";
		String nextlocstr = "";
		try {
			str = readFile(getFilesDir().getAbsolutePath());
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			JSONArray json_array = new JSONArray(str);
			System.out.println(json_array.get(0));
			locations = new LocationDetails[json_array.length()];
			for(int i = 0; i < json_array.length(); i++){
				JSONObject json_data = (JSONObject) json_array.get(i);
				namestr = json_data.getString("Name");
				descriptionstr = json_data.getString("Description");
				latitudestr = json_data.getString("Latitude");
				longitudestr = json_data.getString("Longitude");
				imagestr = json_data.getString("Image");
				nextlocstr = json_data.getString("NextLocationID");
				locstr = json_data.getString("LocationID");
				
				// store the locations for later use
				locations[i]=new LocationDetails(locstr, latitudestr, longitudestr, nextlocstr, namestr, descriptionstr, imagestr);
				
				if(nextlocstr.equals("0")) {
					// this is the last link in the supply chain so focus map here
					map.getController().setCenter(getPoint(Double.parseDouble(latitudestr), Double.parseDouble(longitudestr)));
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		projection = map.getProjection();
		map.getOverlays().add(new SitesOverlay(marker));
		//map.getController().setCenter(getPoint(40.76793169992044, -73.98180484771729));
		me=new MyLocationOverlay(context, map);
		map.getOverlays().add(me);
		
	}
  
	@Override
	public void onResume() {
		super.onResume();
    
		me.enableCompass();
	}   
  
	@Override
	public void onPause() {
		super.onPause();
    
		me.disableCompass();
	}   
  
	@Override
	protected boolean isRouteDisplayed() {
		return(false);
	}
  
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_S) {
			map.setSatellite(!map.isSatellite());
			return(true);
		}
		else if (keyCode == KeyEvent.KEYCODE_Z) {
			map.displayZoomControls(true);
			return(true);
		}
  
		return(super.onKeyDown(keyCode, event));
	}

	private GeoPoint getPoint(double lat, double lon) {
		return(new GeoPoint((int)(lat*1000000.0), (int)(lon*1000000.0)));
	}
	
	private String readFile(String path) throws FileNotFoundException, IOException {
		Intent intent = getIntent();
		String message = intent.getStringExtra(Main.BARCODE);
		FileInputStream stream = new FileInputStream(new File(path+"/" + message + "location.json"));
		FileChannel fc = stream.getChannel();
		MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
		String str = Charset.defaultCharset().decode(bb).toString();
		stream.close();
		return str;
	}
    
	
	private class SitesOverlay extends ItemizedOverlay<OverlayItem> {
		public SitesOverlay(Drawable marker) {
			super(marker);
			boundCenterBottom(marker);
			if(locations != null) {
				for(int i=0; i<locations.length; i++) {
					items.add(new OverlayItem(
							getPoint(Double.parseDouble(locations[i].getLatitude()), 
									Double.parseDouble(locations[i].getLongitude())),
							locations[i].getName(),
							locations[i].getName()+"=="+locations[i].getDescription()+"=="+locations[i].getImage()));
				}
			}
			populate();
		}
		
		public void draw(Canvas canvas, MapView mapv, boolean shadow){
	        super.draw(canvas, mapv, shadow);

			for(int i=0; i<locations.length; i++) {
				Paint mPaint = new Paint();
				mPaint.setDither(true);
		        mPaint.setColor(Color.RED);
		        mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
		        mPaint.setStrokeJoin(Paint.Join.ROUND);
		        mPaint.setStrokeCap(Paint.Cap.ROUND);
		        mPaint.setStrokeWidth(2);
		        if(locations != null) {
					if(locations[i].getNext() != "0") {
						// loop over locations
						for(int j = 0; j < locations.length; j++) {
							// find location which matches next location of current location i
							if(locations[j].getLocation().equals(locations[i].getNext())) {
		
						        // create first point at location i with a nextLocation
						        GeoPoint gP1 = getPoint(Double.parseDouble(locations[i].getLatitude()),
						        		Double.parseDouble(locations[i].getLongitude()));
						        
						        // create second point at nextLocation of first point i
						        GeoPoint gP2 = getPoint(Double.parseDouble(locations[j].getLatitude()),
						        		Double.parseDouble(locations[j].getLongitude()));
		
						        Point p1 = new Point();
						        Point p2 = new Point();
						        Path path = new Path();
						        // draw line between both points
						        projection.toPixels(gP1, p1);
						        projection.toPixels(gP2, p2);
		
						        path.moveTo(p2.x, p2.y);
						        path.lineTo(p1.x,p1.y);
		
						        canvas.drawPath(path, mPaint);
						        
						        break;
							}
			        	}
			        }					
				}else {
					System.out.println("You stuffed up big time");
				}
			}
	    }    
    
		@Override
		protected OverlayItem createItem(int i) {
			return(items.get(i));
		}
  
		
		@Override
		protected boolean onTap(int i) {
			System.out.println(items.get(i).getSnippet());
			String[] locationinfo = items.get(i).getSnippet().split("==");
			TextView tv = (TextView)findViewById(R.id.locationname);
			tv.setText(locationinfo[0]);
			tv.setTextSize(20);
			tv.setTypeface(Typeface.DEFAULT_BOLD);

			TextView tv1 = (TextView)findViewById(R.id.locationdescription);
			tv1.setText(locationinfo[1]);
			tv1.setTextSize(20);
			System.out.println("http://www.cpt3004.dynalias.org:81/cpt/phpappfixed/"+locationinfo[2]);
	        try {
	            
	            ImageView image = (ImageView) findViewById(R.id.googleimage);
	            getImage gi = new getImage(context, image);
	            gi.execute(locationinfo[2]);
	            
	            
	        } catch (Exception e) {
	        	System.out.println("oh shit");
	        	e.printStackTrace();
	        }

		
			return(true);
		}
    
		@Override
		public int size() {
			return(items.size());
		}
	}
}